/*
 * GeoVISTA Center (Penn State, Dept. of Geography)
 * Copyright (c) 2002, GeoVISTA Center
 * Licensed under Simplified BSD License
 * This library is developed and distributed for free usage,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * You can redistribute and/or modify it under the terms of the
 * Simplified BSD License
 *
 *
 *
 *
 *
 *
 *
 * @original author: jin Chen 
 * @author: jin Chen 
 * @date: Jan 12, 2008$
 * @version: 1.0
 */
package edu.psu.geovista.app.vit.pub.components.sts;

import edu.psu.geovista.app.vit.pub.VitPub;
import edu.psu.geovista.db.dbase.DBaseFile;
import edu.psu.geovista.ui.event.SelectionEvent;
import edu.psu.geovista.ui.event.SelectionListener;
import org.apache.commons.io.FileUtils;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import java.io.IOException;
import java.util.*;

public class SSReader extends javax.swing.JPanel implements SelectionListener {

    boolean testing=false;
    double significantRisk=1.0/20.0;
    Map<Object, SSResult> results;
    SSResult result;
    Object sessionId;// 
    String relativeRiskFile; // 

    DynamicTree dtree;
    JFrame frm;
    JScrollPane sp;

    JFrame matrixfrm;


    VitPub application;
    /** Creates new form SatScan */
    PropertyChangeSupport pcs;//=new PropertyChangeSupport(this);
    public static final String PROP_CHANGE_SESSION = "Show_Another_Session";

    public SSReader() {
        initComponents();
        customize();
    }

    /*******************************************************************************************************
     *                services
     *******************************************************************************************************/

    public void showMaps(){


    }
    public void loadSatScanData(){


        String roots="F:\\work\\App\\Cancer\\SatScan\\jinAdam7";
        JFileChooser fs=new JFileChooser(new File(roots));
        fs.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        Object[]   buttons=new Object[]{"OK","Cancel"};
        String title="Please choose the SatScan cluster file ";
        int value=JOptionPane.showOptionDialog(this, fs,title,
                JOptionPane.YES_NO_OPTION,
                JOptionPane.PLAIN_MESSAGE ,
                null,
                buttons,
                buttons[0]);
        int i = value;
        if(i== JOptionPane.YES_OPTION){
            //show up table
            String fn=null;
            if(this.isTesting() ){
                System.out.println("testing");
            }
            else{
                File selectedFile = fs.getSelectedFile();
                fn = selectedFile.getPath();//fs.getFileName();
            }
            loadSaTScanResults(fn);
        }
    }
    public  void loadSaTScanResults (final String fn){

                           /* frm.setVisible(true);
                            frm.setAlwaysOnTop(true);*/
         loadSaTScan(fn);
    }

    private  void loadSaTScan(String fn) {
        this.inputFileFd.setText(fn);
        final File file=new File(fn);
        if(file.isFile()){
                dtree.clear();
                loadClusters(fn);
                if(! this.isTesting() ){

                this.showDialog();
            }
        }
        else if (file.isDirectory()){
            //FileUtils.listFiles(file,new String[]{".gis.dbf"}, true) ;
            JTree tree = dtree.getTree();
            Object root = tree.getModel().getRoot();
            int count = tree.getModel().getChildCount(root);
            if(count>0){
                int v = JOptionPane.showConfirmDialog(this, "Clear existing sessions?");
                if(v==JOptionPane.OK_OPTION){
                    dtree.clear() ;
                }
            }

            loadSaTScanSessions(file);
            dtree.revalidate() ;
            this.dtree.repaint();
            if(! this.isTesting() ){
                this.showDialog();
            }
        }
    }

    private void loadSaTScanSessions(File file) {
        java.util.List<File> gisFiles = getGisFiles(file);
        for (Iterator fileIterator = gisFiles.iterator(); fileIterator.hasNext();) {
            File f = (File) fileIterator.next();
            try {

                   loadASaTScanClusters(f);
                            double pvalue = this.getSignificantRisk();
                            selectSignificantRegions(pvalue);


            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }

    private void showDialog(){
        if(sp==null)sp=new JScrollPane(this);
        if(frm==null)frm=new JFrame("SaTScan results");

        Container container=frm.getRootPane().getContentPane();
        container.add(sp);
        frm.setSize(800,600);
        frm.setVisible(true);
       // frm.show();
    }
    public static void showDialog(JFrame frm,JComponent c, Dimension size){
        JScrollPane sp=new JScrollPane(c);
        if(frm==null)frm=new JFrame("SaTScan results");

        Container container=frm.getRootPane().getContentPane();
        container.add(sp);
        frm.setSize(size);
        frm.setVisible(true);
        frm.show();
    }
    private java.util.List<File> getGisFiles(File dir){
        Collection collection = FileUtils.listFiles(dir, new String[]{"dbf"}, true);
        Set<File> gisFiles=new HashSet<File>();
        for (Iterator fileIterator = collection.iterator(); fileIterator.hasNext();) {
            File f = (File) fileIterator.next();
            String s = f.getName();
            if(s.indexOf(".gis.dbf")>0 ){
                gisFiles.add(f);
            }
            //System.out.println("");
        }
        ArrayList files=new ArrayList(gisFiles);
//        FileService.FileNameComparator comp=new FileService.FileNameComparator();
        class FileNamePercentageComparator extends SSResult.PerentageComparator {
            public int compare(Object o1, Object o2) {
                File f1= (File) o1;
                File f2= (File) o2;
                String n1 = f1.getName();
                String n2 = f2.getName();
                //return super.compare(n1,n2);

                double p1 = getPercentage(n1);
                double p2 = getPercentage(n2);
                return Double.compare(p1,p2);
            }
        }//inner class
        try {
            // SatScanResult.PerentageComparator comp=new SatScanResult.PerentageComparator();
            FileNamePercentageComparator comp=new FileNamePercentageComparator();
            Collections.sort(files,comp);
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return files;
        //System.out.println("");
    }

    private void loadASaTScanClusters(File file) throws IOException {
        String fn = file.getCanonicalPath();
        loadClusters(fn);

    }

    /**
     *  
     *  
     * @param gisfn      
     */
    private void loadClusters(String gisfn){  // 
        try {
            File myf=new File(gisfn);
            String sessionId = myf.getName().replaceAll(".gis.dbf","");// 
            SSResult ssr=new SSResult(sessionId);

            //read gis file
            DBaseFile gisdbf =new DBaseFile(gisfn);
            Object[] gisdataSet = gisdbf.getDataSet();
            MyTableModel gismodel=new MyTableModel();
            gismodel.feedData(gisdataSet);
            ssr.setFileGisdbf(gisfn);
            ssr.setDataGisdbf(gismodel);
            //read col file
            try {
               String  colfn=gisfn.replaceAll(".gis.dbf" , ".col.dbf");
                DBaseFile coldbf=new DBaseFile(colfn);
                Object[]  coldataSet = coldbf.getDataSet();
                MyTableModel colmodel=new MyTableModel();
                colmodel.feedData(coldataSet);
                ssr.setDataColdbf(colmodel);
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

            // 
            String rrfn=gisfn.replaceAll(".gis.dbf" , ".rr.dbf");
            setRelativeRiskFile(rrfn);

            this.results.put(sessionId,ssr);
            this.dtree.addToRoot(sessionId);
            showSession(sessionId);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    /**
     * show a session in the tables
     */
    public  void showSession(Object sessionId){
        this.setSessionId(sessionId);
        result = this.results.get(sessionId);
        if(result==null){
            JOptionPane.showMessageDialog(this,"Unable to find session "+sessionId);
            return;
        }
        Map<Object, Set> clusterGroup = result.getClusterGroup();
        DefaultTableModel clusterTablemodel = result.getClusterRecordTable();
        DefaultTableModel dataTablemodel = result.getDataRecordTable();

        MyTable ctable = (MyTable) getClusterTable();
        MyTable rtable = (MyTable) getRecordTable();

        ctable.setDataGroups(clusterGroup);

        rtable.setFireSelectionEvents(false);
        ctable.setFireSelectionEvents(false);

        ctable.setModel(clusterTablemodel);
        rtable.setModel(dataTablemodel);
        ctable.setFireSelectionEvents(true);
        rtable.setFireSelectionEvents(true);

        Set<Integer> selClusterIds = result.getSelClusterIds();
        if(selClusterIds.size() >0){
            int[] selrows = ctable.getRowIndexsByIDs(selClusterIds);
            System.out.println("showSession "+sessionId+" set selection "+selrows.length );
            ctable.selectRows(selrows);
        }
        this.pcs.firePropertyChange(PROP_CHANGE_SESSION,null,sessionId);

    }

   

    /**************************************************
     *                significant clusters/data items
     ***************************************************/
    private void askSignificantValue(){
        double pvalue = this.getSignificantRisk();
        String spv=String.valueOf(pvalue) ;
        String spvalue = JOptionPane.showInputDialog("Please set the p-value ", spv);
        pvalue = Double.valueOf(spvalue.trim());
        this.setSignificantRisk(pvalue);

    }

    /**
     * update results (Satscan results): select only  clusters  that has significant < given <pvalue>.
     * results (Satscan results) provides selected clusters when u switch to another session.
     * @param pvalue
     */
    public  void selectSignificantRegions( double pvalue){

        Collection<SSResult> satScanResults = results.values();
        for (Iterator satScanResultIterator = satScanResults.iterator(); satScanResultIterator.hasNext();) {
            SSResult rt = (SSResult) satScanResultIterator.next();
            DefaultTableModel clusterTable = rt.getClusterRecordTable();
            Set<Integer> significantClusterIds = getSignificantIds(pvalue, clusterTable);
            rt.setSelClusterIds(significantClusterIds);
        }
    }
    private void clearSelections(){
        Collection<SSResult> satScanResults = results.values();
        for (Iterator satScanResultIterator = satScanResults.iterator(); satScanResultIterator.hasNext();) {
            SSResult rt = (SSResult) satScanResultIterator.next();
            rt.setSelClusterIds(null);
        }
    }

   
    public java.util.List<SSResult> getSortResultsByPerentage(){
        Map<Object, SSResult> map = this.getResults();
        Collection<SSResult> results = map.values();
        ArrayList resultlist=new ArrayList(results);
        SSResult.SatScanResultIdPercentageComparotor comp=new SSResult.SatScanResultIdPercentageComparotor();
            Collections.sort(resultlist, comp);
        return resultlist;
    }
    public Map<Object,Double> getReliableValue(double pvalue){
        double totalCount = results.size();
        // 
        // 
        Map<Object,Integer> signficantCounts=new HashMap<Object, Integer>();
        setSignificantRisk(pvalue);
        Collection<SSResult> satScanResults = results.values();
        for (Iterator satScanResultIterator = satScanResults.iterator(); satScanResultIterator.hasNext();) {
            SSResult rt = (SSResult) satScanResultIterator.next();
            DefaultTableModel clusterTable = rt.getClusterRecordTable();
            Set<Integer> significantClusterIds = getSignificantIds(pvalue, clusterTable);
            rt.setSelClusterIds(significantClusterIds);
            Set dataIds = rt.getDataIds();
            //update count for each dataid in the dataIds
            for (Iterator iterator = dataIds.iterator(); iterator.hasNext();) {
                Object dataid = (Object) iterator.next();
                Integer count = signficantCounts.get(dataid);
                if(count==null) count=0;
                count++;
                signficantCounts.put(dataid,count);

            }
        }

        Map<Object,Double> signficantPcts=new HashMap<Object, Double>(); // // 
        Set<Object> dataids = signficantCounts.keySet();
        for (Iterator objectIterator = dataids.iterator(); objectIterator.hasNext();) {
            Object dataid = (Object) objectIterator.next();
            Integer count = signficantCounts.get(dataid);
            if(count==null)count=0;
            double pct=count/totalCount;
            signficantPcts.put(dataid,pct);
        }
        return signficantPcts;
    }

    /**
     *
     * @param pvalue
     * @param sessionIds
     * @return            a map. Key:  dataid, value: it reliability value
     */
     public Map<Object,Double> getReliableValue(double pvalue, Set sessionIds){
       boolean  workonAllSession=false;
       if(sessionIds==null||sessionIds.size() ==0) workonAllSession=true; //no selection given, work on all session

        // 
        // 
        Map<Object,Integer> signficantCounts=new HashMap<Object, Integer>();
        setSignificantRisk(pvalue);
         //calculate count that  a place (of the data id) is reported in a high risk cluster
         Collection<SSResult> satScanResults = results.values();
        for (Iterator satScanResultIterator = satScanResults.iterator(); satScanResultIterator.hasNext();) {
            SSResult rt = (SSResult) satScanResultIterator.next();
            if(workonAllSession||sessionIds.contains(rt.getSessionId())){
                //work only for selected sessions. if no selected session, then works for all session
                DefaultTableModel clusterTable = rt.getClusterRecordTable();
                Set<Integer> significantClusterIds = getSignificantIds(pvalue, clusterTable);
                rt.setSelClusterIds(significantClusterIds);
                Set dataIds = rt.getDataIds(); // 
                //update count for each dataid in the dataIds
                for (Iterator iterator = dataIds.iterator(); iterator.hasNext();) {
                    Object dataid = (Object) iterator.next();
                    Integer count = signficantCounts.get(dataid);
                    if(count==null) count=0;
                    count++;
                    signficantCounts.put(dataid,count);

                }
            }
        }
        //calculate percentage based on the count
        double totalCount = workonAllSession? results.size():sessionIds.size() ;
        Map<Object,Double> signficantPcts=new HashMap<Object, Double>(); // // 
        Set<Object> dataids = signficantCounts.keySet();
        for (Iterator objectIterator = dataids.iterator(); objectIterator.hasNext();) {
            Object dataid = (Object) objectIterator.next();
            Integer count = signficantCounts.get(dataid);
            if(count==null)count=0;
            double pct=count/totalCount;
            signficantPcts.put(dataid,pct);
        }
        return signficantPcts;
    }

    /**
     * get the data id for selected clusters in cluster table, which by default are the significant clusters
     * @param sessionId
     * @return
     */
    public Set getSelectedDataIds(Object sessionId){
        SSResult rt = getSatScanResult(sessionId);
        return rt.getDataIds();
    }
    public SSResult getSatScanResult(Object sessionId){
        return results.get(sessionId);
    }


   
    /*******************************************************************************************************
     *                set/get
     *******************************************************************************************************/
    /**
     * set a mapping btw ID (e.g., FIPS code) to index
     * @param id2Index
     */
    public void setID2Index(Map<Object, Integer> id2Index) {
        ((MyTable) this.clusterTable).setId2IndexMap( id2Index); //setId2IndexMap
        ((MyTable) this.recordTable).setId2IndexMap( id2Index); //setId2IndexMap
    }

    public MyTable getClusterTable() {
        return (MyTable)clusterTable;
    }

    public JTable getRecordTable() {
        return recordTable;
    }


    public boolean isTesting() {
        return testing;
    }

    public void setTesting(boolean testing) {
        this.testing = testing;
    }

   /* public Object[] getShpdata() {
        return shpdata;
    }

    public void setShpdata(Object[] shpdata) {
        this.shpdata = shpdata;
    }*/

    public Map<Object, SSResult> getResults() {
        return results;
    }

    public void setResults(Map<Object, SSResult> results) {
        this.results = results;
    }

    public VitPub getApplication() {
        return application;
    }

    public void setApplication(VitPub application) {
        this.application = application;
    }

    public String getRelativeRiskFile() {
        return relativeRiskFile;
    }

    public void setRelativeRiskFile(String relativeRiskFile) {
        this.relativeRiskFile = relativeRiskFile;
    }
    // public Object[] getSessionId

      /*******************************************************************************************************
     *                events
     *******************************************************************************************************/

    public void addSelectionListener (SelectionListener l) {          //addSelectionListener
        ((MyTable) this.clusterTable).addSelectionListener(l); //setId2IndexMap
        ((MyTable) this.recordTable).addSelectionListener(l); //setId2IndexMap
    }

    /**
     * removes an SelectionListener from the component
     */
    public void removeSelectionListener (SelectionListener l) {
        ((MyTable) this.clusterTable).removeSelectionListener(l); //setId2IndexMap
        ((MyTable) this.recordTable).removeSelectionListener(l); //setId2IndexMap
    }
    public void addPropertyChangeListener(PropertyChangeListener l){
          this.pcs.addPropertyChangeListener(l);
    }
    /*******************************************************************************************************
     *                GUI
     *******************************************************************************************************/
    protected void customize(){
        results=new HashMap<Object, SSResult>();
        clusterTable=new MyTable();
        clusterTable.setFont(new Font("Arial",Font.PLAIN,16));
        clusterTable.setRowHeight(20);
        final MyTable ct= (MyTable) clusterTable;
        ct.setColumnName_ID(SSResult.Colname_ClusterID);
        ct.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                        {null, null, null, null,null,null},
                        {null, null, null, null,null},
                        {null, null, null, null,null}
                },
                new String [] {
                        SSResult.Colname_ClusterID, SSResult.Colname_Size, SSResult.Colname_PVALUE, SSResult.Colname_CLU_ODE, SSResult.Colname_CLU_Risk
                }
        ));
        ListSelectionModel selectionModel = ct.getSelectionModel();
        selectionModel.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                int[] selectedrows = ct.getSelectedRows();
                Set selClusterIds = getClusterTable().getSelectedId(selectedrows);
                //HashSet selRows = CollectionUtils.convertArrayToSet(selectedrows);
                if(selectedrows.length >0){
                    // 
                    // 
                    result.setSelClusterIds(selClusterIds);
                }
            }
        });


        clusterTableSp.setViewportView(ct);

        recordTable=new MyTable();
        recordTable.setFont(new Font("Arial",Font.PLAIN,16));
        recordTable.setRowHeight(20);
        MyTable rt= (MyTable) recordTable;
        rt.setColumnName_ID(SSResult.Colname_RecordID);
        rt.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null}
                },
                new String [] {
                        SSResult.Colname_RecordID, SSResult.Colname_ClusterID, SSResult.Colname_Size, SSResult.Colname_PVALUE
                }
        ));
        recordTableSp.setViewportView(rt);

        //tree
        final DynamicTree dtree=new DynamicTree("SaTScan Outcomes");
        dtree.getTree().addTreeSelectionListener(new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent e) {
                JTree tree =(JTree) e.getSource();
                //TreePath[] paths=e.getPaths() ;  //get only lastest selection
                TreePath[] paths=tree.getSelectionModel().getSelectionPaths(); //get whole selection
                if(paths==null)return;
                for (int i=0;i<paths.length ;i++){
                    DefaultMutableTreeNode node=(DefaultMutableTreeNode) paths[i].getLastPathComponent() ;
                    String nodeName=(String) node.getUserObject() ;
                    showSession(nodeName);

                    System.out.println(" Select nodes:   "+nodeName);
                }
            }
        });

        JTree tree = dtree.getTree();
        Font f = tree.getFont();
        tree.setFont(new Font(f.getName(),Font.PLAIN,18));
        tree.setRowHeight(30);
             //jScrollPane1.setViewportView(dtree);
        this.dtree =dtree;
        this.treepane.add(dtree);  //jin added


       pcs=new PropertyChangeSupport(this);
    }

    public double getSignificantRisk() {
        return significantRisk;
    }

    public void setSignificantRisk(double significantRisk) {
        this.significantRisk = significantRisk;
    }

    public Object getSessionId() {
        return sessionId;
    }

    public void setSessionId(Object sessionId) {
        this.sessionId = sessionId;
    }

    public Set getSessionIds(){
        return this.results.keySet();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    protected  void initComponents() {
        this.treepane=new JPanel();              //jin added
        treepane.setLayout(new BorderLayout());
        controlPane = new javax.swing.JPanel();
        addSBtn = new javax.swing.JButton();
        rmvSBtn = new javax.swing.JButton();
        clrSBtn = new javax.swing.JButton();
        saveBtn = new javax.swing.JButton();
        selHighRiskBtn = new javax.swing.JButton();
        clearSelBtn = new javax.swing.JButton();
        loadPopBtn = new javax.swing.JButton();
        jSplitPane1 = new javax.swing.JSplitPane();
        topPane = new javax.swing.JPanel();
        jSplitPane2 = new javax.swing.JSplitPane();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        sessionTree = new javax.swing.JTree();
        jPanel5 = new javax.swing.JPanel();
        clusterTableSp = new javax.swing.JScrollPane();
        clusterTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        inputFileFd = new javax.swing.JTextField();
        btmPane = new javax.swing.JPanel();
        recordTableSp = new javax.swing.JScrollPane();
        recordTable = new javax.swing.JTable();

        controlPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        addSBtn.setText("Add session");
        addSBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addSBtnActionPerformed(evt);
            }
        });

        rmvSBtn.setText("Clear all sessions");
        rmvSBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rmvSBtnActionPerformed(evt);
            }
        });

        clrSBtn.setText("Remove session");
        clrSBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clrSBtnActionPerformed(evt);
            }
        });

        saveBtn.setText("Save");
        saveBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveBtnActionPerformed(evt);
            }
        });

        selHighRiskBtn.setText("Select high risk");
        selHighRiskBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selHighRiskBtnActionPerformed(evt);
            }
        });

        clearSelBtn.setText("Clear selections");
        clearSelBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearSelBtnActionPerformed(evt);
            }
        });



        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(controlPane);
        controlPane.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
                jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .add(addSBtn)
                        /*.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(clrSBtn)
                        .add(14, 14, 14)
                        .add(rmvSBtn)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(saveBtn)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(selHighRiskBtn)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(clearSelBtn)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(loadPopBtn)*/
                        .addContainerGap(289, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
                jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                .add(addSBtn)
                                /*.add(clrSBtn)
                                .add(rmvSBtn)
                                .add(saveBtn)
                                .add(selHighRiskBtn)
                                .add(clearSelBtn)
                                .add(loadPopBtn)*/)
                        .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jSplitPane1.setDividerLocation(250);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jSplitPane2.setDividerLocation(300);

       // jScrollPane1.setViewportView(sessionTree);

        org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
                jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(treepane , org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE)
        );   //jScrollPane1
        jPanel4Layout.setVerticalGroup(
                jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(treepane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE)
        );  //jScrollPane1

        jSplitPane2.setLeftComponent(jPanel4);

        clusterTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null}
                },
                new String [] {
                        "Title 1", "Title 2", "Title 3", "Title 4"
                }
        ));
        clusterTableSp.setViewportView(clusterTable);

        jLabel1.setText("SatScan .gis file");

        org.jdesktop.layout.GroupLayout jPanel5Layout = new org.jdesktop.layout.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
                jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(jPanel5Layout.createSequentialGroup()
                                .addContainerGap()
                                .add(jLabel1)
                                .add(13, 13, 13)
                                .add(inputFileFd, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 607, Short.MAX_VALUE))
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, clusterTableSp, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 706, Short.MAX_VALUE)
        );
        jPanel5Layout.setVerticalGroup(
                jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(jPanel5Layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                .add(jLabel1)
                                .add(inputFileFd, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(15, 15, 15)
                        .add(clusterTableSp, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE))
        );

        jSplitPane2.setRightComponent(jPanel5);

        org.jdesktop.layout.GroupLayout topPaneLayout = new org.jdesktop.layout.GroupLayout(topPane);
        topPane.setLayout(topPaneLayout);
        topPaneLayout.setHorizontalGroup(
                topPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(jSplitPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 1012, Short.MAX_VALUE)
        );
        topPaneLayout.setVerticalGroup(
                topPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(jSplitPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
        );

        jSplitPane1.setTopComponent(topPane);

        recordTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null}
                },
                new String [] {
                        "Title 1", "Title 2", "Title 3", "Title 4"
                }
        ));

        recordTableSp.setViewportView(recordTable);

        org.jdesktop.layout.GroupLayout btmPaneLayout = new org.jdesktop.layout.GroupLayout(btmPane);
        btmPane.setLayout(btmPaneLayout);
        btmPaneLayout.setHorizontalGroup(
                btmPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(recordTableSp, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 1012, Short.MAX_VALUE)
        );
        btmPaneLayout.setVerticalGroup(
                btmPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, recordTableSp)
        );

        jSplitPane1.setRightComponent(btmPane);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 1014, Short.MAX_VALUE)
                        .add(controlPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                        .add(controlPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 679, Short.MAX_VALUE)
                        .addContainerGap())
        );
    }// </editor-fold>



    private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {

    }

    private void clrSBtnActionPerformed(java.awt.event.ActionEvent evt) {

    }

    private void rmvSBtnActionPerformed(java.awt.event.ActionEvent evt) {

    }

    private void addSBtnActionPerformed(java.awt.event.ActionEvent evt) {
        loadSatScanData();
    }
    private void selHighRiskBtnActionPerformed(java.awt.event.ActionEvent evt) {

    }

    private void clearSelBtnActionPerformed(java.awt.event.ActionEvent evt) {

    }






    // Variables declaration - do not modify
    protected javax.swing.JButton addSBtn;
    protected javax.swing.JPanel btmPane;
    protected javax.swing.JButton clearSelBtn;
    protected javax.swing.JButton clrSBtn;
    protected javax.swing.JTable clusterTable;
    protected javax.swing.JScrollPane clusterTableSp;
    protected javax.swing.JTextField inputFileFd;
    protected javax.swing.JLabel jLabel1;
    protected javax.swing.JPanel controlPane;
    protected javax.swing.JPanel jPanel4;
    protected javax.swing.JPanel jPanel5;
    protected javax.swing.JScrollPane jScrollPane1;
    protected javax.swing.JSplitPane jSplitPane1;
    protected javax.swing.JSplitPane jSplitPane2;
    protected javax.swing.JButton loadPopBtn;
    protected javax.swing.JTable recordTable;
    protected javax.swing.JScrollPane recordTableSp;
    protected javax.swing.JButton rmvSBtn;
    protected javax.swing.JButton saveBtn;
    protected javax.swing.JButton selHighRiskBtn;
    protected javax.swing.JTree sessionTree;
    protected javax.swing.JPanel topPane;
    protected JPanel treepane;
    // End of variables declaration

    

    public void selectionChanged(SelectionEvent event) {
       // System.out.println("");
    }

    /**
     *
     * @param riskvalue    
    * @return    
    */
   public static Set getSignificantIds(Double riskvalue, DefaultTableModel clusterTable){
       //DefaultTableModel clusterTable = this.getClusterRecordTable();

       MyTableModel model=new MyTableModel(clusterTable);
       Vector pvalues = model.getColumn(SSResult.Colname_PVALUE);
       Vector clusterIds = model.getColumn(SSResult.Colname_ClusterID);

       Set<Integer> riskIds=new HashSet<Integer>();
       int index=0;
       for (Iterator iterator = pvalues.iterator(); iterator.hasNext();) {
           Double pv = (Double) iterator.next();
           if(pv<=riskvalue){
               riskIds.add((Integer) clusterIds.get(index));
           }
           index++;
       }
       return riskIds;
   }



}
